<?php

class AddressManager extends TModule
{
	// -------------------- basic functions --------------------
	public function addAddress($country, $city, $postal_code, $street, $number, $description)
	{
		$element = new AddressRecord();
		$element->setData(0, $country, $city, $postal_code, $street, $number, $description);
		
		if($element->save())
			return $element;
		else
			return null;
	}
	
	public function deleteAddress($id)
	{
		return AddressRecord::finder()->deleteById($id);
	}
	
	public function updateAddress($id, $country, $city, $postal_code, $street, $number, $description)
	{	
		$elementRecord = new AddressRecord();
		$elementRecord->setData($id, $country, $city, $postal_code, $street, $number, $description);
		return $this->updateAddressByAddressRecord($elementRecord);
	}

	public function updateAddressByAddressRecord($elementRecord)
	{	
		if($elementRecord instanceof AddressRecord)
		{
			$finder = AddressRecord::finder();
			$id = $elementRecord->getId();
			if($id > 0 && $rec = $finder->findByPk($id))
			{
				if($rec->equals($elementRecord))
					return $rec;
				$rec->setDataByAddressRecord($elementRecord);
				if($rec->save())
					return $rec;
			}
		}
		return null;
	}
	
	public function getAddressById($id)
	{
		return AddressRecord::finder()->findById($id);
	}
	
	// -------------------- extended functions --------------------
	public function getAddressesList($revert = false, $offset = -1, $limit = -1)
	{
		$criteria = new TActiveRecordCriteria();
		
		if($revert)
			;//$criteria->OrdersBy['start_datetime'] = 'desc';
			
		if($offset < 0 || $offset == null)
			$offset = 0;
		if($limit < 0 || $limit == null)
			$limit = $this->countAddresss();
			
		$criteria->Offset = $offset;
		$criteria->Limit = $limit;
		
		return AddressRecord::finder()->findAll($criteria);
	}
	
	public function countAddresses()
	{
		return AddressRecord::finder()->count();
	}
}

?>